<template>
    <div class="layout">
        <div v-if="!isLoading && !isTableList" class="no-data-box">
            <div class="title-box">
                <img class="title-img" src="@/assets/smartMarketing/community/icon_01.png" />
                <div class="title-content">
                    <div class="title-name">社群打卡</div>
                    <div class="title-desc">
                        群打卡，不仅可以提升老客户的积极性，而且在一定程度上还可以增加用户粘性，提升群聊活跃度及转化率。借助社群管理工具来做长期签到的活动，用户只需要每天在群内签到打卡，打卡送积分或小礼品，以此来激发群员参与的热情。
                    </div>
                    <el-button class="title-button" type="primary" @click="onOpenUse">去使用</el-button>
                </div>
            </div>
            <div class="scene-box">
                <div class="scene-box-title">营销场景</div>
                <div class="scene-box-img">
                    <img
                        class="scene-img"
                        src="https://img.static-keyid.cn/toolspace/scrm/2023/08/1692010392265njstx2l9b4k9z1c8.png" />
                </div>
                <div class="desc-content">
                    <div class="desc-title">推广流程如下：</div>
                    <div class="desc-text">
                        1、群主可将打卡话术设置成入群欢迎语，在新用户进入群聊之后将推送该打卡活动的欢迎语，让新用户也能快速参与到我们的打卡活动中来。
                    </div>
                    <div class="desc-text">
                        2、群主可将打卡话术添加到群公告中，方便群内的成员使用，以免社群太活跃，导致刚发出去没多久的打卡通知被刷上去了，而导致客户看不到活动说明。
                    </div>
                    <div class="desc-text">
                        3、同时，使用客户群群发工具或客户群SOP，由企业管理员或是员工群发，将打卡活动群发到客户群中，邀请客户参与。
                    </div>
                    <div class="desc-text">
                        4、员工可在客户详情中可以查看群活动，并将群活动发送到当前群聊中，邀请客户发送打卡口令参与活动。
                    </div>
                    <div class="desc-text">
                        5、登录企业微信管理后台，在【客户与上下游】-【聊天工具】-【自动回复】中，将推广链接设置为打卡自动回复语。并在群聊中开启自动回复，群成员可以每天在群聊中@小助理，发送打卡口令，如“签到”，在群内打卡成功，并收到打卡记录查看链接。
                    </div>
                </div>
            </div>
        </div>
        <div v-show="!isLoading && isTableList" class="container">
            <div class="container-form">
                <ZwSearchForm
                    row-num="4"
                    default-expand
                    :option="searchOption"
                    @search="search"
                    @reset="reset"
                    @expand="onExpand" />
            </div>
            <div class="container-table">
                <div class="container-table-account">
                    <ShareAccountConfiguration
                        ref="shareAccountConfigurationRef"
                        :is-show-official-accounts="false"
                        :type="12"
                        :no-need-loading="true"
                        @auth="fissionAuth" />
                    <el-button type="primary" @click="onOpenNew">新建活动</el-button>
                </div>
                <ZwTable
                    ref="tableRef"
                    class="table-box"
                    tab-h="initial"
                    :fetch-api="fetchApi()"
                    :row-key="getRowKey"
                    :close-loading="true"
                    :option="tableOption"
                    :fetch-params="state.searchParams"
                    @updateData="getTableData">
                </ZwTable>
            </div>
        </div>
        <PlugDialog :id="plugInfoId" v-model="plugShow" />
    </div>
</template>
<script setup lang="tsx">
import ZwSearchForm from '@/components/zw/search-form1.0/SearchForm';
import ZwTable from '@/components/zw/table1.0/Table';
import ShareAccountConfiguration from '@/components/common/ShareAccountConfiguration.vue';
import PlugDialog from './PlugDialog.vue';

import { ref, reactive, computed, onMounted, markRaw } from 'vue';
import { useRouter } from 'vue-router';

import { WarningFilled } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getCreateList } from '@/api/common';

import { deepCopy } from '@/utils/helper';

import {
    getHaveAvailable,
    punchCardListApi,
    punchCardOver,
    punchCardDel
} from '@/api/smartMarketing/community/communityCheckIn';

const router = useRouter();

const tableRef: any = ref<HTMLElement | null>(null);

const isLoading = ref<boolean>(true);
const isTableList = ref<boolean>(false);
const isTableSearch = ref<boolean>(false);

const authInfo = ref<any>({});

const shareAccountConfigurationRef = ref<any>(null);

/**
 * 推广弹框：true-展示 false-关闭
 */
const plugShow = ref<boolean>(false);

/**
 * 推广弹框：活动id
 */
const plugInfoId = ref<any>('');

/**
 * 状态颜色
 */
const StatusColorOption = {
    未开始: '#EAEAEA',
    进行中: '#2FB6E4',
    已结束: '#F14144'
};

const defaultParams = {
    activity_name: '', // 活动名称
    clock_password: '',
    create_uid: [], //创建人
    activity_status: -1 //活动状态
};

const state = reactive({
    searchParams: deepCopy(defaultParams)
});

const searchOption = computed(() => {
    return [
        {
            label: '活动名称',
            name: 'activity_name',
            value: '',
            type: 'input',
            placeholder: '请输入活动名称'
        },
        {
            label: '活动状态',
            name: 'activity_status',
            value: '',
            type: 'select',
            placeholder: '请选择活动状态',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve([
                        { name: '未开始', id: 1 },
                        { name: '进行中', id: 2 },
                        { name: '已结束', id: 3 }
                    ]);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '打卡口令',
            name: 'clock_password',
            value: '',
            type: 'input',
            placeholder: '请输入打卡口令'
        },
        {
            label: '创建人',
            name: 'created_uid',
            value: [],
            multiple: true,
            type: 'select',
            filterable: true,
            placeholder: '请选择创建人',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone})`;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});

const search = (v: any) => {
    isTableSearch.value = true;
    state.searchParams = deepCopy(v);
};
const reset = (v: any) => {
    isTableSearch.value = true;
    state.searchParams = deepCopy(v);
};

const onExpand = () => {};

const tableOption = [
    {
        prop: 'activity_name',
        label: '活动名称',
        showOverflowTooltip: true,
        minWidth: 230
    },
    {
        prop: 'clock_password',
        label: '打卡口令',
        showOverflowTooltip: true,
        width: 200
    },
    {
        prop: 'activity_status_name',
        label: '活动状态',
        width: 100,
        render({ row }: any) {
            return (
                <div
                    class="activity-status"
                    style={{
                        '--status-bgcolor': StatusColorOption[row.activity_status_name] ?? '#2FB6E4'
                    }}>
                    {row.activity_status_name}
                </div>
            );
        }
    },
    {
        prop: 'clock_time_range',
        label: '打卡时间段',
        width: 150,
        render({ row }: any) {
            const toolTipSlot = () => (
                <div>
                    {row.clock_time_range?.map((el: any) => (
                        <div>
                            {el[0]}-{el[1]}
                        </div>
                    ))}
                </div>
            );
            return (
                <div className={'clock_time_range'}>
                    <div>
                        {row.clock_time_range?.map((el: any, index: number) => {
                            const flag = index == 1 && row.clock_time_range?.length > 2;
                            return (
                                <el-tooltip
                                    effect="dark"
                                    vSlots={{ content: toolTipSlot }}
                                    disabled={!flag}
                                    placement="top-start">
                                    <div v-show={index < 2}>
                                        {el[0]}-{el[1]}
                                        {flag ? '...' : ''}
                                    </div>
                                </el-tooltip>
                            );
                        })}
                    </div>
                </div>
            );
        }
    },
    {
        prop: 'groupchat_list',
        label: '可用群聊',
        width: 150,
        render({ row }: any) {
            return (
                <div>
                    {row.clock_groupchat == 1
                        ? '全部群聊'
                        : row.clock_groupchat == 2
                        ? `指定${row.groupchat_list?.length}个群聊`
                        : '--'}
                </div>
            );
        }
    },
    {
        prop: 'period_type',
        label: '活动有效期',
        width: 170,
        render({ row }: any) {
            return (
                <div>
                    {row.period_type == 1 ? (
                        '永久'
                    ) : (
                        <div>
                            <span>{row.activity_time[0]}</span>
                            <span> - </span>
                            <span>{row.activity_time[1]}</span>
                        </div>
                    )}
                </div>
            );
        }
    },
    {
        prop: 'created_user',
        label: '创建人',
        showOverflowTooltip: true,
        width: 120
    },
    {
        prop: 'updated_at',
        label: '更新时间',
        width: 180
    },
    {
        prop: 'operate',
        label: '操作',
        width: 210,
        fixed: 'right',
        isOperate: true,
        option: [
            {
                name: '编辑',
                authCode: 'EDIT',
                isRender: ({ row }: any) => [1, 2].includes(row.activity_status),
                click: (row: any) => onEdit(row)
            },
            {
                name: '查看',
                authCode: 'LOOK',
                click: (row: any) => onLook(row)
            },
            {
                name: '删除',
                authCode: 'DEL',
                isRender: ({ row }: any) => [1, 3].includes(row.activity_status),
                click: (row: any) => onDelete(row)
            },
            {
                name: '推广',
                authCode: 'PLUG',
                isRender: ({ row }: any) => [1, 2].includes(row.activity_status),
                click: (row: any) => onPopularize(row)
            },
            {
                name: '结束',
                authCode: 'END',
                isRender: ({ row }: any) => [2].includes(row.activity_status),
                click: (row: any) => onEnd(row)
            },
            {
                name: '数据',
                authCode: 'STATISTICS',
                isRender: ({ row }: any) => [2, 3].includes(row.activity_status),
                click: (row: any) => onRecord(row)
            }
        ]
    }
];
/**
 * key
 */
const getRowKey = (row: any) => {
    return row.id;
};

const fetchApi = () => {
    return punchCardListApi;
};

/**
 * 获取列表数据
 * @param list table数据
 */
const getTableData = (list?: any) => {
    isLoading.value = false;
    // isTableList.value = !!list.length;
    if (!isTableSearch.value && !list.length) {
        isTableList.value = false;
    } else {
        isTableList.value = true;
    }
};

/**
 * 去使用
 */
const onOpenUse = async () => {
    if (!(await onCheck())) return;
    // isTableList.value = true;
    onDetail('new');
};

/**
 * 新建活动
 */
const onOpenNew = async () => {
    if (!(await onCheck())) return;
    onDetail('new');
};

/**
 * 编辑
 */
const onEdit = (val: any) => {
    onDetail('edit', val);
};

/**
 * 查看
 */
const onLook = (val: any) => {
    onDetail('look', val);
};

/**
 * 删除
 */
const onDelete = async (val: any) => {
    await ElMessageBox.confirm('确定要删除此活动吗？', '提示', {
        customClass: 'community-checkin-msg-box-confirm',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        icon: markRaw(WarningFilled)
    });
    await punchCardDel({ activity_id: val.activity_id });
    tableRef.value.reload();
    ElMessage.success('删除成功');
};

/**
 * 推广
 */
const onPopularize = async (val: any) => {
    plugInfoId.value = val.activity_id;
    plugShow.value = true;
};

/**
 * 结束
 */
const onEnd = async (val: any) => {
    await ElMessageBox.confirm('确定要提前结束此活动吗？', '提示', {
        customClass: 'community-checkin-msg-box-confirm',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        icon: markRaw(WarningFilled)
    });
    await punchCardOver({ activity_id: val.activity_id });
    tableRef.value.reload();
    ElMessage.success('提前结束成功');
};

/**
 * 数据
 */
const onRecord = (val: any) => {
    router.push({
        path: '/smartMarketing/community/communityCheckIn/dataStatistics',
        query: { activity_id: val.activity_id }
    });
};

/**
 * 前往详情页
 * @param type new-新建, edit-编辑, look-查看
 * @param val 活动数据
 */
const onDetail = (type: string, val: any = {}) => {
    router.push({
        path: '/smartMarketing/community/communityCheckIn/detail',
        query: { type: type, id: val.activity_id }
    });
};

// 获取配置权限
const fissionAuth = (val: any) => {
    !!val && (authInfo.value = val);
};

/**
 * 校验
 */
const onCheck = async () => {
    // 是否开通会话存档：1开通，0未开通
    const { is_open_session_archive } = await getHaveAvailable();
    if (is_open_session_archive != 1) {
        await ElMessageBox.confirm('此功能需要开通企微会话存档，请前往开通', '提示', {
            customClass: 'community-checkin-msg-box-confirm',
            confirmButtonText: '前往开通',
            cancelButtonText: '取消',
            type: 'warning',
            icon: markRaw(WarningFilled)
        });
        window.open('/channelconfig/qywechat/messagesave');
        return false;
    }
    // 是否配置小程序
    if (!authInfo.value.mini_program_id || authInfo.value.is_set_mini != 2) {
        await ElMessageBox.confirm('此功能需要使用小程序，请先配置打卡小程序', '提示', {
            customClass: 'community-checkin-msg-box-confirm',
            confirmButtonText: '去配置',
            cancelButtonText: '取消',
            type: 'warning',
            icon: markRaw(WarningFilled)
        });
        shareAccountConfigurationRef.value.configurationMiniProgram();
        return false;
    }
    return true;
};

onMounted(() => {});
</script>
<style lang="scss" scoped>
.layout {
    .no-data-box {
        width: 100%;

        .title-box {
            display: flex;
            padding: 16px 16px 16px 24px;
            border: 1px solid #eaeaea;
            border-radius: 4px;
            background-color: #fff;

            .title-img {
                margin-right: 16px;
                min-width: 101px;
                height: 101px;
            }

            .title-content {
                .title-name {
                    font-size: 20px;
                    font-family: PingFangSC-Medium, 'PingFang SC';
                    font-weight: 500;
                    color: #33302d;
                    line-height: 28px;
                }

                .title-desc {
                    padding-top: 4px;
                    font-size: 14px;
                    font-family: PingFangSC-Regular, 'PingFang SC';
                    font-weight: 400;
                    color: #33302d;
                    line-height: 20px;
                }

                .title-button {
                    margin-top: 16px;
                }
            }
        }

        .scene-box {
            margin-top: 16px;
            padding: 24px;
            border: 1px solid #eaeaea;
            border-radius: 4px;
            background-color: #fff;

            .scene-box-title {
                display: flex;
                align-items: center;
                font-size: 16px;
                font-family: PingFangSC-Medium, 'PingFang SC';
                font-weight: 500;
                color: #333;
                line-height: 16px;

                &::before {
                    width: 3px;
                    height: 16px;
                    margin-right: 6px;
                    content: '';
                    border-radius: 2px;
                    background-color: #ff6b00;
                }
            }

            .scene-box-img {
                margin: 30px 16px 20px;
                max-width: 1332px;
            }

            .scene-img {
                width: 100%;
                height: 100%;
            }

            .desc-content {
                padding-left: 38px;
                font-size: 14px;
                line-height: 22px;

                .desc-title {
                    font-family: PingFangSC-Medium, 'PingFang SC';
                    font-weight: 500;
                    color: #33302d;
                }

                .desc-text {
                    color: #585858;
                }
            }
        }
    }

    .container {
        height: calc(100vh - 142px);
        display: flex;
        flex-direction: column;

        .container-form {
            border: 1px solid #eaeaea;
        }

        .container-table {
            display: flex;
            flex-direction: column;
            overflow: hidden;
            box-sizing: border-box;
            border: 1px solid #eaeaea;
            background-color: #fff;
            padding: 16px;
            margin-top: 16px;
            flex: 1;

            .zw-table {
                display: flex;
                flex-direction: column;
                flex: 1;
                overflow: hidden;

                :deep(.el-table) {
                    flex: 1;

                    .el-table__empty-block {
                        position: absolute;
                        top: 50%;
                        left: 50%;
                        transform: translate(-50%, -50%);
                    }
                }
            }

            .container-table-account {
                display: flex;
                justify-content: space-between;
            }
        }
    }

    :deep(.activity-status) {
        --status-bgcolor: #2fb6e4;

        &::before {
            content: '';
            display: inline-block;
            width: 8px;
            height: 8px;
            margin-right: 8px;
            background-color: var(--status-bgcolor);
            border-radius: 4px;
        }
    }

    :deep(.clock_time_range) {
        height: 46px;
        display: flex;
        align-items: center;
    }

    :deep(.zw-table__com_table.el-table .el-table__body tbody tr td) {
        padding: 8.5px 0;
    }
}
</style>
<style lang="scss">
.community-checkin-msg-box-confirm {
    width: 400px;

    .el-message-box__content {
        padding: 0;
    }

    .el-message-box__container {
        margin: 42px 25px 44px;
        display: flex;
        justify-content: center;
        align-items: center;

        .el-icon {
            position: relative;
            top: 0;
            transform: translateY(0);

            --el-messagebox-color: #faad14;
        }
    }

    .el-message-box__message {
        padding: 0 0 0 8px;
    }

    .el-button--primary {
        background-color: var(--el-button-bg-color) !important;
    }
}
</style>
